package com.lucky.common.utils;

import com.lucky.common.exception.SystemException;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.*;
import java.util.UUID;

public class FileUtil {

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

    /**
     * 生成html文件
     * @param context Context对象(存放Model)
     * @param templateName 模板名称
     * @param filePath 输出路径
     * @param fileName 输出文件名
     * @throws SystemException
     */
    public static void generateFile(Context context,String templateName,String filePath,String fileName) throws SystemException{
        if(!fileExists(filePath)) {
            throw new SystemException("create file fail");
        }
        //创建模版加载器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        //模板文件的所在目录
        resolver.setPrefix("templates/blog/temp/");
        //模板文件后缀
        resolver.setSuffix(".html");
        //创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        //将加载器放入模板引擎
        templateEngine.setTemplateResolver(resolver);
        //创建字符输出流并且自定义输出文件的位置和文件名
        FileWriter writer = null;
        try {
            String filePathName = filePath + fileName;
            writer = new FileWriter(filePathName);
            //模板html名字
            templateEngine.process(templateName, context, writer);
        } catch (IOException e) {
            throw new SystemException(e.getMessage());
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}

    private static boolean fileExists(String filePath){
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            return targetFile.mkdirs();
        }
        return true;
    }
}
